package v1

import (
	"ginblog/model"
	"ginblog/utils/errormsg"
	"ginblog/utils/validator"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

var (
	code int
)

// AddUser 增加用户
func AddUser(c *gin.Context) {
	var data model.User
	var msg string
	_ = c.ShouldBindJSON(&data)
	msg, code = validator.Validate(&data)
	if code != errormsg.SUCCESS {
		c.JSON(http.StatusOK, gin.H{
			"code": errormsg.SUCCESS,
			"msg":  msg,
		})
		return
	}

	code = model.CheckUser(data.Username)
	if code == errormsg.ERROR_USERNAME_USED {
		code = errormsg.ERROR_USERNAME_USED
	} else if code == errormsg.SUCCESS {
		model.AddUser(&data)
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errormsg.GetErrorMsg(code),
		"data":    data,
	})
}

// FindUsers 查找用户列表
func FindUsers(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	if pageSize == 0 {
		pageSize = -1 // -1 表示不使用
	}
	if pageNum == 0 {
		pageNum = -1 // -1 表示不使用
	}
	//调用model下面的查询用户函数
	data, total := model.GetUsers(pageSize, pageNum)
	code = errormsg.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errormsg.GetErrorMsg(code),
		"data":    data,
		"total":   total,
	})
}

// DeleteUser 删除用户
func DeleteUser(c *gin.Context) {
	var user model.User
	_ = c.ShouldBindJSON(&user)
	id, _ := strconv.Atoi(c.Param("id"))
	code = model.DeleteUser(id)
	if code == errormsg.ERROR {
		code = errormsg.ERROR
	}
	code = errormsg.SUCCESS

	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errormsg.GetErrorMsg(code),
	})
}

// UpdateUser 编辑用户
func UpdateUser(c *gin.Context) {
	//1.先进行判断传入的新的用户名称是否存在
	var user model.User
	_ = c.ShouldBindJSON(&user)
	code = model.CheckUser(user.Username)
	if code == errormsg.ERROR_USERNAME_USED {
		c.Abort() //中断本次修改操作的后续函数的调用
	}
	//2.进行用户信息修改操作
	id, _ := strconv.Atoi(c.Param("id"))
	if code == errormsg.SUCCESS {
		code = model.UpdateUser(id, &user)
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errormsg.GetErrorMsg(code),
	})
}
